﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using HelloMinasan.Framework.Web;
using HelloMinasan.Framework.Helpers;
using HelloMinasan.UserDefinedType;
using HelloMinasan.Framework.Web.ActionFilters;

namespace HelloMinasan.Web.Song
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private WebSessionStorage webSessionStorage;

        /// <summary>
        /// Due to issues on IIS7, the NHibernate initialization must occur in Init().
        /// But Init() may be invoked more than once; accordingly, we introduce a thread-safe
        /// mechanism to ensure it's only initialized once.
        /// See http://msdn.microsoft.com/en-us/magazine/cc188793.aspx for explanation details.
        /// </summary>
        public override void Init()
        {
            base.Init();
            this.webSessionStorage = new WebSessionStorage(this);
        }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "TestQuiz", // Route name
                "Song/EditTest/{id}/{testId}", // URL with parameters
                new
                {
                    controller = "Song",
                    action = "EditTest",
                    id = UrlParameter.Optional,
                    testId = UrlParameter.Optional
                } // Parameter defaults
            );
            routes.MapRoute(
                "TestBlank", // Route name
                "Song/EditBlank/{id}/{testId}", // URL with parameters
                new
                {
                    controller = "Song",
                    action = "EditBlank",
                    id = UrlParameter.Optional,
                    testId = UrlParameter.Optional
                } // Parameter defaults
            );
            routes.MapRoute(
                "SongAdmin", // Route name
                "Admin/SongControl/{pageNumber}/{keyword}/{username}", // URL with parameters
                new
                {
                    controller = "Admin",
                    action = "SongControl",
                    pageNumber = UrlParameter.Optional,
                    keyword = UrlParameter.Optional,
                    username = UrlParameter.Optional
                } // Parameter defaults
            );
            routes.MapRoute(
                "FavouriteSong", // Route name
                "UserManagement/MyFavouriteSongs/{pageNumber}/{keyword}", // URL with parameters
                new
                {
                    controller = "UserManagement",
                    action = "MyFavouriteSongs",
                    pageNumber = UrlParameter.Optional,
                    keyword = UrlParameter.Optional
                } // Parameter defaults
            );
            routes.MapRoute(
                "FriendsList", // Route name
                "UserManagement/MyFriendsList/{pageNumber}/{keyword}", // URL with parameters
                new
                {
                    controller = "UserManagement",
                    action = "MyFriendsList",
                    pageNumber = UrlParameter.Optional,
                    keyword = UrlParameter.Optional
                } // Parameter defaults
            );

            routes.MapRoute(
                "Song", // Route name
                "Song/{action}/{id}", // URL with parameters
                new { controller = "Song", action = "Songs", id = UrlParameter.Optional } // Parameter defaults
            );

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}/{page}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional, page = UrlParameter.Optional } // Parameter defaults
            );



        }

        protected void Application_Start()
        {
			ViewEngines.Engines.Clear();
			ViewEngines.Engines.Add(new RazorViewEngine());
			
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            //Route301Global.ReAssignHandler(RouteTable.Routes);
        
            ModelBinders.Binders.DefaultBinder = new HelloMinasanModelBinder();

            ComponentRegistrar.RegisterComponents("HelloMinasan.Web.Song");
            //AutoMapperConfiguration.Configure();

            HelloMinasan.Resources.Resource.ResourceManager.IgnoreCase = true;
            //HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
        }
        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            bool urlChanged = false;
            string url = Request.Url.AbsoluteUri;
            
            //TODO: Delete from char "#" -> DONE BUT NEED TO THINK MORE SO TEMPORARY COMMENT
            //if (url != null)
            //{
            //    int cutCharIndex = url.IndexOf("#");
            //    url = url.Remove(cutCharIndex);
            //}

            if (url != null && url.Contains("/Dictionary/"))
                url = url.ToLower(); //TODO: cannot do this ALL as there are so many url will be redirrected such as image, css, js, etc.

            ////declare new url and lower URL to redirect from upcase to lowercase.
            //TODO: Hien tai chua the lam duoc cho phan '/' cung nhu lower case vi all ajax call se bi error.
            url = url.Replace("www.hellominasan", "hellominasan");//.TrimEnd('/').ToLower();

            if (!url.Equals(Request.Url.AbsoluteUri))
                urlChanged = true;

            ////TODO: will be delete as this is just for debug on local
            //if (Request.Url.AbsoluteUri.Equals("http://localhost:1594/"))
            //    urlChanged = false;

            if (urlChanged)
            {
                //mark as 301
                Response.Status = "301 Moved Permanently";
                Response.StatusCode = 301;
                Response.AppendHeader("Location", url);
            }

            if (!Request.IsSecureConnection && Configuration.GeneralSetting.EnableHttps)
            {
                url = string.Format("https{0}", Request.Url.AbsoluteUri.Substring(4));
                Response.Redirect(url);
            }
        }
    }
}